package com.mm.spring_ext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PeopleBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
	protected Class getBeanClass(Element element) {
		return People.class;
	}

	protected void doParse(Element element, BeanDefinitionBuilder bean) {
		String name = element.getAttribute("name");
		String age = element.getAttribute("age");
		String id = element.getAttribute("id");
		NodeList elementSons = element.getChildNodes();
		if (StringUtils.hasText(id)) {
			bean.addPropertyValue("id", id);
		}
		if (StringUtils.hasText(name)) {
			bean.addPropertyValue("name", name);
		}
		if (StringUtils.hasText(age)) {
			bean.addPropertyValue("age", Integer.valueOf(age));
		}
		if (elementSons != null && elementSons.getLength() > 0) {
			List<String> list = new ArrayList<String>();
			Map<String, String> myMap = new HashMap<String, String>();
			for (int i = 0; i < elementSons.getLength(); i++) {
				Node node = elementSons.item(i);
				if (node instanceof Element) {
					if ("own".equals(node.getNodeName()) || "own".equals(node.getLocalName())) {
						String value = ((Element) node).getAttribute("value");
						list.add(value);
					}
					if ("map".equals(node.getNodeName()) || "map".equals(node.getLocalName())) {
						String key = ((Element) node).getAttribute("key");
						String value = ((Element) node).getAttribute("value");
						myMap.put(key, value);
					}
				}
			}
			bean.addPropertyValue("own", list);
			bean.addPropertyValue("myMap", myMap);
		}

	}
}
